package com.apes.enquiry.enquiry.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.apes.enquiry.brand.model.SpBrand;
import com.apes.enquiry.brand.repository.SpBrandRepository;
import com.apes.enquiry.enquiry.model.*;
import com.apes.enquiry.enquiry.repository.*;
import com.apes.enquiry.product.model.Category;
import com.apes.enquiry.product.model.SpProduct;
import com.apes.enquiry.product.model.TyreProduct;
import com.apes.enquiry.product.repository.SpCategoryRepository;
import com.apes.enquiry.product.repository.SpProductRepository;
import com.apes.enquiry.supplier.baturu.service.BaturuInquireService;
import com.apes.enquiry.product.repository.TyreProductRepository;
import com.apes.enquiry.voluntaryOffers.service.MatchingRuleService;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.express.FuncAlias;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.car.model.CarConfiguration;
import com.apes.scm.masterdata.car.model.CarLabel;
import com.apes.scm.masterdata.car.model.CarModel;
import com.apes.scm.masterdata.car.repository.CarConfigurationRepository;
import com.apes.scm.masterdata.car.repository.CarLabelRepository;
import com.apes.scm.masterdata.car.repository.CarModelRepository;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.repository.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Calendar.DAY_OF_MONTH;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;

/**
 * 类描述：供应商询价单
 *
 * @ClassName EnquiryService
 * @Description 描述
 * @Author wushilong
 * @Date 2023/3/20 11:40
 * @Version 1.0
 */
@Service
public class EnquiryService extends DomainService {

    @Autowired
    private EnquiryRepository enquiryRepository;

    @Autowired
    private EnquiryRequireRepository enquiryRequireRepository;

    @Autowired
    private EnquiryItemRepository enquiryItemRepository;

    @Autowired
    private QuoteRepository quoteRepository;

    @Autowired
    private QuoteItemRepository quoteItemRepository;

    @Autowired
    private QuoteResultRepository quoteResultRepository;

    @Autowired
    private SpBrandRepository spBrandRepository;

    @Autowired
    private SpProductRepository spProductRepository;

    @Autowired
    private FirstBrandRepository firstBrandRepository;

    @Autowired
    private PartyRoleRepository roleRepository;

    @Autowired
    private EnquiryDao enquiryDao;
    @Autowired
    private SpCategoryRepository categoryRepository;

    @Autowired
    private PartyRoleRepository partyRoleRepository;

    @Autowired
    private BusinessParamRepository businessParamRepository;
    @Autowired
    private OutboxSubscriberService outboxSubscriberService;

    @Autowired
    private BaturuInquireService baturuInquireService;

    @Autowired
    private InquiryService inquiryService;


    /**
     * 开始询价
     *
     * @param request
     */
    public void enquiry(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        //配件询价
        categoryEnquiry(requestJO.getJSONObject("categoryParam"));
        //轮胎询价
        tyreEnquiry(requestJO.getJSONObject("tyreParam"));
        //改装配件询价
        refitCategoryEnquiry(requestJO.getJSONObject("refitParam"));
    }

    /**
     * 配件询价
     * @param param
     */
    private void categoryEnquiry(JSONObject param){
        if (Objects.isNull(param))return;

        //构建询价单
        Enquiry enquiry = newEnquiry(param,"parts");
        EnquiryDataDto enquiryDataDto = new EnquiryDataDto();
        enquiryDataDto.setEnquiry(enquiry);
        enquiryDataDto.setOrigin(param.getString("origin"));
        //构建询价配件
        List<EnquiryItem> enquiryItems = newEnquiryItemAndQuote(param, enquiry);
        enquiryDataDto.setEnquiryItem(enquiryItems);
        enquiryDataDto.setPartyRole(JSONObject.parseObject(param.getString("platform"),PartyRole.class));
        inquiryService.inquireData(enquiryDataDto);
    }

    /**
     * 轮胎询价
     * @param param
     */
    private void tyreEnquiry(JSONObject param){
        if (Objects.isNull(param))return;

        //构建询价单
        Enquiry enquiry = newEnquiry(param,"tyre");
        //构建询价轮胎
        tyreEnquiryItemAndQuote(param, enquiry);
    }

    /**
     * 配件询价
     * @param param
     */
    private void refitCategoryEnquiry(JSONObject param){
        if (Objects.isNull(param))return;

        //构建询价单
        Enquiry enquiry = newEnquiry(param,"refit");
        //构建询价配件
        newEnquiryItemAndQuote(param, enquiry);
    }

    /**
     * 根据ID查询
     *
     * @param request
     */
    public Enquiry findByID(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        return enquiryRepository.findOne(requestJO.getString("id"));

    }

    /**
     * 判断报价结果是否过期
     * @param request
     * @return
     */
    public boolean findQuoteResultState(SimpleRequest request){
        String offerId = request.get("id");
        int index = offerId.indexOf("/");
        String quoteResultId = offerId.substring(0, index);
        QuoteResult quoteResult  =quoteResultRepository.findOne(quoteResultId);
        if(quoteResult==null){
            return false;
        }
        if("20".equals(quoteResult.getState())){
            return false;
        }
        return true;
    }

    /**
     * 构建询价单
     *
     * @param requestJO
     * @param type 询价单类型：0是配件，1是轮胎
     * @return
     */
    private Enquiry newEnquiry(JSONObject requestJO, String type) {
        Enquiry enquiry = new Enquiry();
        JSONObject fnCustomerExpand = requestJO.getJSONObject("fnCustomerExpand");
        enquiry.setServicePlanId(requestJO.getString("servicePlan"));
        enquiry.setVin(fnCustomerExpand.getString("vin"));
        enquiry.setVendorCode(fnCustomerExpand.getString("vendorCode"));
        enquiry.setCarLicense(fnCustomerExpand.getString("carLicense"));
        enquiry.setRepeatedlyOrderDate(new Date());

        CarLabel carLabel = new CarLabel();//厂牌
        if (Objects.isNull(getBean(CarLabelRepository.class).findOne(requestJO.getJSONObject("carLabel").getString("id")))) {
            carLabel.setId(requestJO.getJSONObject("carLabel").getString("id"));
            carLabel.setName(requestJO.getJSONObject("carLabel").getString("name"));
            carLabel.setCarBrand(requestJO.getJSONObject("carLabel").getString("carBrand"));
            carLabel.setManufacturers(requestJO.getJSONObject("carLabel").getString("manufacturers"));
            carLabel = getBean(CarLabelRepository.class).saveAndFlush(carLabel);
        } else {
            carLabel = getBean(CarLabelRepository.class).findOne(requestJO.getJSONObject("carLabel").getString("id"));
        }
        enquiry.setVehicleLabel(carLabel);

        CarModel carModel = new CarModel();//车型
        if (Objects.isNull(getBean(CarModelRepository.class).findOne(requestJO.getJSONObject("carModel").getString("id")))) {
            carModel.setId(requestJO.getJSONObject("carModel").getString("id"));
            carModel.setName(requestJO.getJSONObject("carModel").getString("name"));
            carModel.setCarLabel(carLabel);
            carModel = getBean(CarModelRepository.class).saveAndFlush(carModel);
        } else {
            carModel = getBean(CarModelRepository.class).findOne(requestJO.getJSONObject("carModel").getString("id"));
        }

        CarConfiguration carConfiguration = new CarConfiguration();//车型配置
        if (Objects.isNull(getBean(CarConfigurationRepository.class).findOne(requestJO.getJSONObject("fnCustomer").getString("id")))) {
            carConfiguration.setName(requestJO.getJSONObject("fnCustomer").getString("name"));
            carConfiguration.setId(requestJO.getJSONObject("fnCustomer").getString("id"));
            carConfiguration.setCarLabel(carLabel);
            carConfiguration.setCarModel(carModel);
            carConfiguration = getBean(CarConfigurationRepository.class).saveAndFlush(carConfiguration);
        } else {
            carConfiguration = getBean(CarConfigurationRepository.class).findOne(requestJO.getJSONObject("fnCustomer").getString("id"));
        }
        enquiry.setVehicleConfig(carConfiguration);

        enquiry.setAutoBrand(requestJO.getJSONObject("carLabel").getString("carBrand"));
        enquiry.setStore(requestJO.getJSONObject("store").getString("id"));
        enquiry.setStoreName(requestJO.getJSONObject("store").getString("name"));
        enquiry.setContacts(requestJO.getJSONObject("employee").getString("name"));
        enquiry.setContactPhone(requestJO.getJSONObject("employee").getString("mobileNumber"));
        enquiry.setAddress(requestJO.getJSONObject("store").getString("address"));
        enquiry.setSum(requestJO.getJSONArray("categoryItem").size());
        enquiry.setBeInvoice(requestJO.getBoolean("beInvoice"));
        enquiry.setState("ing");
        BusinessParam businessParam = businessParamRepository.findOne("1");
        Date quoteExpireDate = DateUtil.add(new Date(), DAY_OF_MONTH, Integer.parseInt(businessParam.getValue()));//系统时间+7天
        enquiry.setQuoteExpireDate(quoteExpireDate);
        if (StringUtils.isNotEmpty(requestJO.getString("pictures")) && !"[]".equals(requestJO.getString("pictures"))) {
            enquiry.setPictures(requestJO.getString("pictures"));
        }
        enquiry.setType(type);
        if ("refit".equals(type)){
            enquiry.setProductRule(true);
        }
        /*enquiry.setCarHead("");
        enquiry.setCarTail("");
        enquiry.setNameplate("");*/

        return enquiryRepository.saveAndFlush(enquiry);
    }

    /**
     * 构建询价配件明细
     *
     * @param requestJO
     * @param enquiry
     * @return
     */
    private List<EnquiryItem> newEnquiryItemAndQuote(JSONObject requestJO, Enquiry enquiry) {
        JSONArray categoryItems = requestJO.getJSONArray("categoryItem");
        JSONArray suppliers = requestJO.getJSONArray("supplierAndCategories");
        List<String> supplierIds = suppliers.stream().map((item -> ((JSONObject) item).getString("supplierId"))).collect(toList());
        List<String> distinctSupplierId = supplierIds.stream().distinct().collect(toList());

        distinctSupplierId.forEach(supplierId -> {
            PartyRole supplier = getBean(PartyRoleRepository.class).findOne(supplierId);
            //判断供应商是否注册
            if (Objects.nonNull(supplier)){
                //报价单
                newQuote(supplierId, enquiry);
            }
        });

        Map<String, EnquiryItem> enquiryItemMap = new HashMap<>();
        List<EnquiryItem> enquiryItems = new ArrayList<>();
        for (Object o : categoryItems) {
            JSONObject categoryItem = (JSONObject) o;
            //询价需求
            EnquiryRequire enquiryRequire = newEnquiryRequire(categoryItem, enquiry);
            //询价配件
            EnquiryItem enquiryItem = newEnquiryItem(enquiry, enquiryRequire, categoryItem);
            enquiryItems.add(enquiryItem);
            enquiryItemMap.put(categoryItem.getString("id"), enquiryItem);
        }
        //根据供应商构建报价配件
        for (Object s : suppliers) {
            JSONObject supplier = (JSONObject) s;
            //获取报价单
            Quote quote = quoteRepository.findOneByEnquiryAndSupplier(enquiry.getId(), supplier.getString("supplierId"));
            if (Objects.isNull(quote)) continue;
            //获取询价配件
            EnquiryItem enquiryItem = enquiryItemMap.get(supplier.getJSONObject("serviceItem").getString("id"));
            //报价配件
            QuoteItem quoteItem = newQuoteItem(supplier, quote, enquiryItem);
            //构建系统报价结果
            newQuoteResult(enquiry, enquiryItem, quote, quoteItem);
        }
        enquiryItemRepository.flush();
        return enquiryItems;
    }

    /**
     * 构建轮胎询价明细
     * @param requestJO
     * @param enquiry
     */
    private void tyreEnquiryItemAndQuote(JSONObject requestJO, Enquiry enquiry) {
        JSONArray categoryItems = requestJO.getJSONArray("categoryItem");
        JSONArray suppliers = requestJO.getJSONArray("supplierAndCategories");
        List<String> supplierIds = suppliers.stream().map((item -> ((JSONObject) item).getString("supplierId"))).collect(toList());
        List<String> distinctSupplierId = supplierIds.stream().distinct().collect(toList());

        distinctSupplierId.forEach(supplierId -> {
            PartyRole supplier = getBean(PartyRoleRepository.class).findOne(supplierId);
            //判断供应商是否注册
            if (Objects.nonNull(supplier)){
                //报价单
                newQuote(supplierId, enquiry);
            }
        });

        Map<String, EnquiryItem> enquiryItemMap = new HashMap<>();
        for (Object o : categoryItems) {
            JSONObject categoryItem = (JSONObject) o;
            //询价需求
            EnquiryRequire enquiryRequire = newEnquiryRequire(categoryItem, enquiry);
            //询价配件
            EnquiryItem enquiryItem = tyreEnquiryItem(enquiry, enquiryRequire, categoryItem);
            enquiryItemMap.put(categoryItem.getString("id"), enquiryItem);
        }
        //根据供应商构建报价配件
        for (Object s : suppliers) {
            JSONObject supplier = (JSONObject) s;
            //获取报价单
            Quote quote = quoteRepository.findOneByEnquiryAndSupplier(enquiry.getId(), supplier.getString("supplierId"));
            if (Objects.isNull(quote)) continue;
            //获取询价配件
            EnquiryItem enquiryItem = enquiryItemMap.get(supplier.getJSONObject("serviceItem").getString("id"));
            //报价配件
            QuoteItem quoteItem = newQuoteItem(supplier, quote, enquiryItem);
            //预报价轮胎
            if (StringUtils.isNotEmpty(enquiryItem.getProductId())){
                newQuoteResultTyre(enquiry, enquiryItem, quote, quoteItem);
            }
        }
    }



    //构建系统报价结果
    private void newQuoteResult(Enquiry enquiry, EnquiryItem enquiryItem, Quote quote, QuoteItem quoteItem){
        SimpleRequest srt = new SimpleRequest();
        //匹配系统报价商品
        srt.setData(MapUtil.mapper("PZCXID", enquiry.getVehicleConfig().getId(), "category", enquiryItem.getCategory(), "OE", enquiryItem.getOe()));
        List products = getBean(MatchingRuleService.class).meaningfulProduct(srt);
        JSONArray productArray = JSONArray.parseArray(JSON.toJSONString(MapUtil.mapped(products)));
        JSONArray filterProduct = productArray.stream().filter(o -> {
            JSONObject product = (JSONObject) o;
            return product.getJSONObject("product").getJSONObject("supplier").getString("id").equals(quote.getPartyRoleId());
        }).collect(toCollection(JSONArray::new));
        //设置系统报价商品标记
        List<QuoteResult> quoteResults = filterProduct.stream().map(o -> {
            JSONObject item = (JSONObject) o;
            JSONObject productJson = item.getJSONObject("product");
            SpProduct product = spProductRepository.findOne(productJson.getString("id"));
            QuoteResult quoteResult = new QuoteResult();
            quoteResult.setEnquiryId(enquiry.getId());
            quoteResult.setQuoteId(quote.getId());
            quoteResult.setEnquiryItem(enquiryItem.getId());
            quoteResult.setQuoteItem(quoteItem.getId());
            quoteResult.setQuoteOE(MapUtil.mapper("OE", product.getOE()));
            quoteResult.setNotTaxUnitPrice(product.getNotTaxUnitPrice());
            quoteResult.setQuoteBrand(product.getSpBrand());
            quoteResult.setPlaceOfDispatch(0);
            quoteResult.setSupplierId(quote.getPartyRoleId());
            quoteResult.setProduct(product);
            quoteResult.setState("00");
            quoteResult.setNote("");
            quoteResult.setSystem("系统报价");
            quoteResult.setSystemSign(true);
            quoteResult.setPng("[]");
            quoteResult.setQuotaValid(1);

            double taxUnitPrice = product.getNotTaxUnitPrice();
            if (enquiry.getBeInvoice()) {
                String result = (String) invoke("fn.fnEnquiryService.getSupplierTicketPoint", MapUtil.mapper("store", enquiry.getStore(),
                        "supplierId", quote.getPartyRoleId(), "brand", product.getSpBrand().getId()));
                JSONObject body = JSONObject.parseObject(result);
                DecimalFormat df = new DecimalFormat("#.00");//保留小数点后两位
                taxUnitPrice = quoteResult.getNotTaxUnitPrice() * (body.getDoubleValue("body") / 100 + 1.0);//计算含税单价
                taxUnitPrice = Double.parseDouble(df.format(taxUnitPrice));
            }
            //含税单价
            quoteResult.setTaxUnitPrice(taxUnitPrice);
            return quoteResultRepository.saveAndFlush(quoteResult);
        }).collect(toList());
        //有系统报价视为已报价，修改报价配件状态
        if (quoteResults.isEmpty())return;
        quoteItem.setQuoteState("already");
        quoteItemRepository.saveAndFlush(quoteItem);
    }

    /**
     * 构建轮胎预报价
     * @param enquiry
     * @param enquiryItem
     * @param quote
     * @param quoteItem
     */
    private void newQuoteResultTyre(Enquiry enquiry, EnquiryItem enquiryItem, Quote quote, QuoteItem quoteItem){
        //获取轮胎标准配件
        JSONObject tyreProductJSON = invoke("dc.tyreProduct.findOneERPProductId", MapUtil.mapper("productId", enquiryItem.getProductId()));
        if (Objects.isNull(tyreProductJSON)) return;
        PartyRole supplier = partyRoleRepository.findOne(quote.getPartyRoleId());
        TyreProduct tyreProduct = getBean(TyreProductRepository.class).findByAllConditionSupplier(tyreProductJSON.getString("brand"), tyreProductJSON.getString("figure"), tyreProductJSON.getString("loadIndex"),
                tyreProductJSON.getString("speedClass"), tyreProductJSON.getBoolean("antiExplosion"), tyreProductJSON.getString("specification"), quote.getPartyRoleId());
        SpProduct product = null;
        //查找历史数据
        if (Objects.nonNull(tyreProduct)){
            product = tyreProduct.getSpProduct();
        }
        //没有历史数据
        if (Objects.isNull(product)){
            //生成临时商品
            product = newProduct(supplier, tyreProductJSON, enquiryItem, "tyre", enquiry);
        }

        QuoteResult quoteResult = new QuoteResult();
        quoteResult.setEnquiryId(enquiry.getId());
        quoteResult.setQuoteId(quote.getId());
        quoteResult.setEnquiryItem(enquiryItem.getId());
        quoteResult.setQuoteItem(quoteItem.getId());
        quoteResult.setQuoteOE(MapUtil.mapper("OE", product.getOE()));
        quoteResult.setNotTaxUnitPrice(product.getNotTaxUnitPrice());
        quoteResult.setQuoteBrand(product.getSpBrand());
        quoteResult.setPlaceOfDispatch(0);
        quoteResult.setSupplierId(quote.getPartyRoleId());
        quoteResult.setProduct(product);
        quoteResult.setState("00");
        quoteResult.setNote("");
        quoteResult.setPng("[]");
        quoteResult.setSystem("系统报价");
        quoteResult.setNotTaxUnitPrice(0.00);
        quoteResult.setQuotaValid(1);
        quoteResultRepository.saveAndFlush(quoteResult);

    }

    /**
     * 构建询价寻求
     *
     * @param servicePlanItem
     * @param enquiry
     * @return
     */
    private EnquiryRequire newEnquiryRequire(JSONObject servicePlanItem, Enquiry enquiry) {
        EnquiryRequire enquiryRequire = new EnquiryRequire();
        enquiryRequire.setEnquiryId(enquiry.getId());
        enquiryRequire.setNote(servicePlanItem.getString("note"));
        enquiryRequire.setQty(servicePlanItem.getInteger("saleQty"));
        enquiryRequire.setDescribe("");
        enquiryRequire.setOldPicture(servicePlanItem.getString("oldPicture"));
        enquiryRequire.setState("ing");
        return enquiryRequireRepository.saveAndFlush(enquiryRequire);
    }

    /**
     * 构建询价配件
     *
     * @param enquiry
     * @param item
     * @return
     */
    private EnquiryItem newEnquiryItem(Enquiry enquiry, EnquiryRequire enquiryRequire, JSONObject item) {
        EnquiryItem enquiryItem = new EnquiryItem();
        enquiryItem.setEnquiryId(enquiry.getId());
        enquiryItem.setEnquiryRequireId(enquiryRequire.getId());
        enquiryItem.setOe(item.getString("partCode"));
        enquiryItem.setPrice(item.getDouble("price"));
        enquiryItem.setThisPicture(item.getString("thisPicture"));
        enquiryItem.setSmartEpcPartName(item.getString("smartEpcPartName"));

        if (!ObjectUtils.isEmpty(item.getJSONObject("category").getJSONObject("classify"))){
            enquiryItem.setClassifyId(item.getJSONObject("category").getJSONObject("classify").getString("id"));
            enquiryItem.setClassifyName(item.getJSONObject("category").getJSONObject("classify").getString("name"));
        }
        if (StringUtils.isEmpty(item.getJSONObject("category").getString("id"))){
            Category category = JSONObject.parseObject(item.getString("category"), Category.class);
            enquiryItem.setCategoryName(category.getName());
        }else {
            Category category = categoryRepository.findOne(item.getJSONObject("category").getString("id"));
            enquiryItem.setCategoryName(category.getName());
            enquiryItem.setCategoryId(category.getId());
        }

        //EPC图片和旧件图片放一起
        JSONArray epcPicture = JSONArray.parseArray(item.getString("mapAddress"));
        JSONArray oldPicture = JSONArray.parseArray(item.getString("oldPicture"));
        if (Objects.nonNull(epcPicture) && Objects.nonNull(oldPicture)) {
            epcPicture.addAll(oldPicture);
            enquiryItem.setEpcPicture(epcPicture.toJSONString());
        } else {
            enquiryItem.setEpcPicture(null);
            if (Objects.nonNull(epcPicture) && !epcPicture.isEmpty()) {
                enquiryItem.setEpcPicture(item.getString("mapAddress"));
            }
            if (Objects.nonNull(oldPicture) && !oldPicture.isEmpty()) {
                enquiryItem.setEpcPicture(enquiryRequire.getOldPicture());
            }
        }

        enquiryItem.setState("take_effect");
        enquiryItem.setNotQuoteQty(0);
        enquiryItem.setQuoteQty(0);
        enquiryItem.setLackQuoteQty(0);
        enquiryItem.setSendBackQty(0);
        enquiryItem = enquiryItemRepository.saveAndFlush(enquiryItem);
        return enquiryItem;
    }

    private EnquiryItem tyreEnquiryItem(Enquiry enquiry, EnquiryRequire enquiryRequire, JSONObject item){
        EnquiryItem enquiryItem = new EnquiryItem();
        enquiryItem.setEnquiryId(enquiry.getId());
        enquiryItem.setEnquiryRequireId(enquiryRequire.getId());
        enquiryItem.setOe(item.getString("partsCodes"));
        enquiryItem.setPrice(item.getDouble("price"));

        //轮胎
        Category category = categoryRepository.findOne(item.getJSONObject("category").getString("id"));
        enquiryItem.setCategoryName(category.getName());
        enquiryItem.setCategoryId(category.getId());

        //用户上传图片
        JSONArray oldPicture = JSONArray.parseArray(item.getString("oldPicture"));
        if (Objects.nonNull(oldPicture)) {
            enquiryItem.setEpcPicture(oldPicture.toJSONString());
        }
        enquiryItem.setState("take_effect");
        enquiryItem.setProductId(item.getString("productId"));
        enquiryItem.setNotQuoteQty(0);
        enquiryItem.setQuoteQty(0);
        enquiryItem.setLackQuoteQty(0);
        enquiryItem.setSendBackQty(0);
        enquiryItem = enquiryItemRepository.saveAndFlush(enquiryItem);
        return enquiryItem;
    }
    /**
     * 构建报价单
     *
     * @param supplier
     * @param enquiry
     * @return
     */
    private Quote newQuote(String supplier, Enquiry enquiry) {
        Quote quote = new Quote();
        quote.setEnquiryId(enquiry.getId());
        quote.setPartyRoleId(supplier);
        quote.setState("ing");
        return quoteRepository.saveAndFlush(quote);
    }

    /**
     * 构建报价配件
     *
     * @param supplier    供应商及对应配件
     * @param quote       报价单
     * @param enquiryItem 询价配件
     * @return 报价配件
     */
    private QuoteItem newQuoteItem(JSONObject supplier, Quote quote, EnquiryItem enquiryItem) {
        QuoteItem quoteItem = new QuoteItem();
        quoteItem.setQuoteId(quote.getId());
        quoteItem.setPartyRoleId(supplier.getString("supplierId"));
        quoteItem.setEnquiryItemId(enquiryItem.getId());
        quoteItem.setEnquiryRequireId(enquiryItem.getEnquiryRequireId());
        quoteItem.setQuoteState("not");
        quoteItem.setRecognitionState("not");
        quoteItem.setOriginalQuoteQty(0);
        quoteItem.setBrandQuoteQty(0);
        quoteItem.setSameQuoteQty(0);
        quoteItem.setElseQuoteQty(0);
        return quoteItemRepository.saveAndFlush(quoteItem);
    }

    /**
     * 获取询价单明细
     *
     * @param request
     * @return 询价单明细
     */
    public Map findOneEnquiry(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        String id = requestJO.getString("id");
        String supplierName = requestJO.getString("supplierName");
        String supplierId = requestJO.getString("supplierId");
        if (id.startsWith("XJ")) {
            id = requestJO.getString("quoteId");
        }
        Integer page = requestJO.getInteger("page");
        Integer pages = requestJO.getInteger("pages");

        //报价单
        Quote quote = quoteRepository.findOne(id);
        //询价单
        Enquiry enquiry = enquiryRepository.findOne(quote.getEnquiryId());
        if (!StringUtils.isEmpty(supplierName)){
            enquiry.setSupplierName(supplierName);
        }
        enquiry.doExpireDate();//设置报价时间
        enquiry.setQuoteId(quote.getId());//设置报价单号，提交报价使用
        PartyRole supplier = getBean(PartyRoleRepository.class).findOne(quote.getPartyRoleId());
        if (Objects.isNull(supplier)) throw new RuntimeException("当前供应商未开通账号");
        Page<EnquiryItem> enquiryItems;
        if ("yyadmin".equals(supplier.getId())) {
            enquiryItems = enquiryItemRepository.findByEnquiryId(enquiry.getId(), PageRequest.of(page, pages, Sort.by(Sort.Direction.DESC, "id")));
        } else {

            //报价配件
            List<String> enquiryItemIds = quoteItemRepository.findAllQuoteId(quote.getId());
            if (ObjectUtils.isEmpty(pages)){
                pages = enquiryItemIds.size();
            }
            //询价配件
            enquiryItems = enquiryItemRepository.findInId(enquiryItemIds, PageRequest.of(page, pages, Sort.by(Sort.Direction.DESC, "id")));
        }
        //匹配系统报价商品
        enquiryItems.getContent().forEach(enquiryItem -> {
            //已有报价结果
            List<QuoteResult> quoteResultList = new ArrayList<>();
            if ("form/custom.manualQuotation.manualQuotationComponent".equals(requestJO.getString("formId"))) {
                quoteResultList = quoteResultRepository.findAllEnquiryItemAndPriceGTZero(enquiryItem.getId(), supplier.getId(), quote.getId());
            } else {
                quoteResultList = quoteResultRepository.findAllEnquiryItem(enquiryItem.getId(), supplier.getId(), quote.getId());
            }

            quoteResultList.forEach(quoteResult -> {
                if (!"Tyre".equals(quoteResult.getProduct().getStandardType()) || quoteResult.getNotTaxUnitPrice() > 0){
                    quoteResult.setSystemSign(true);
                }
                if("refit".equals(quoteResult.getProduct().getStandardType())){
                    quoteResult.setQuoteOE(MapUtil.mapper("name", quoteResult.getProduct().getName()));
                }else {
                    quoteResult.setQuoteOE(MapUtil.mapper("OE", quoteResult.getProduct().getOE()));
                }

                quoteResult.setExtend(MapUtil.mapped(quoteResult.getProduct().extend()));
            });
            enquiryItem.setQuoteResult(quoteResultList);
            //询价需求
            EnquiryRequire enquiryRequire = enquiryRequireRepository.findOne(enquiryItem.getEnquiryRequireId());
            enquiryItem.setQty(enquiryRequire.getQty());
            enquiryItem.setNote(enquiryRequire.getNote());
            enquiryItem.getCategory();
        });

        Map enquiryMap = MapUtil.mapped(enquiry);
        enquiryMap.put("place", acquireAddress(supplier.getId()));
        Map vehicleConfig = (Map) enquiryMap.get("vehicleConfig");
        vehicleConfig.put("vehicleLabel",enquiryMap.get("vehicleLabel"));
        vehicleConfig.put("carModel", enquiry.getVehicleConfig().getCarModel() == null ? "" : MapUtil.mapped(enquiry.getVehicleConfig().getCarModel().getName()));
        return mapper("enquiry", enquiryMap, "enquiryItem", enquiryItems.getContent(), "size", enquiryItems.getTotalElements(), "page", page);
    }

    /**
     * 零件号下拉框
     *
     * @param request
     * @return 商品列表
     */
    public Map findOE(SimpleRequest request) {
        JSONObject requestJO = request.getJO();

        String param = "%" + requestJO.getString("key") + "%";//用户输入参数
        int page = requestJO.getInteger("page");//分页
        String quoteId = requestJO.getJSONObject("group").getJSONArray("filters").getJSONObject(0).getJSONObject("value").getString("quoteId");//报价单号
        String enquiryItem = requestJO.getJSONObject("group").getJSONArray("filters").getJSONObject(1).getString("value");
        //根据报价单的供应商查询该供应商的商品
        Quote quote = quoteRepository.findOne(quoteId);
        Page<SpProduct> spProducts = spProductRepository.findAllLikeIdAndName(param, quote.getPartyRoleId(), PageRequest.of(page, 20, Sort.by(Sort.Direction.DESC, "id")));
        JSONArray content = JSONArray.parseArray(JSON.toJSONString(MapUtil.mapped(spProducts.getContent())));
        //该报价单已报的商品
        List<QuoteResult> oneQuote = quoteResultRepository.findOneQuote(quoteId, enquiryItem);
        List<String> productIds = oneQuote.stream().map(quoteResult -> quoteResult.getProduct().getId()).collect(toList());
        JSONArray quoteProduct = JSONArray.parseArray(JSON.toJSONString(MapUtil.mapped(oneQuote.stream().map(QuoteResult::getProduct).collect(toList()))));
        //过滤掉已报价的商品
        List<Object> filterContent = content.stream().filter(item -> !productIds.contains(((JSONObject) item).getString("id"))).collect(toList());
        //前端分组需要的参数
        filterContent.forEach(o -> {
            JSONObject item = (JSONObject) o;
            //判修改时间，没有修改过则使用创建时间
            if (Objects.isNull(item.getDate("updateDate"))) {
                Date createDate = item.getDate("createDate");
                SimpleDateFormat sf = new SimpleDateFormat("MM-dd");
                item.put("date", sf.format(createDate));
            } else {
                Date updateDate = item.getDate("updateDate");
                SimpleDateFormat sf = new SimpleDateFormat("MM-dd");
                item.put("date", sf.format(updateDate));
            }
            //分组
            Boolean temporary = item.getBoolean("temporary");
            if (temporary) {
                item.put("group", "历史报价");
            } else {
                item.put("group", "商品");
                item.put("quoteBrand", item.get("spBrand"));
//                item.put("disabled", true);
            }
            item.put("groupBy", "group");

        });
        if (page == 0) {
            //处理已报价商品
            quoteProduct.forEach(o -> {
                JSONObject product = (JSONObject) o;
                product.put("date", "已报");
                product.put("disabled", true);
                product.put("quoteBrand", product.get("spBrand"));
                product.put("group", "商品");
                product.put("groupBy", "group");
            });
            //将报价的添加到结果里面
            filterContent.addAll(quoteProduct);
        }
        filterContent.sort(Comparator.comparing(j -> {
            JSONObject spProduct = (JSONObject) j;
            return spProduct.getString("group");
        }));
        return MapUtil.mapper("content", filterContent, "size", 20, "page", page, "pages", spProducts.getTotalPages(), "total", spProducts.getTotalElements());
    }

    /**
     * 品牌下拉框
     * 品牌排序：把品牌件和另外几个类型分开来查，把品牌件放在最后面
     *
     * @param request
     * @return 品牌列表
     */
    public Map findBrand(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        String personId = request.getPersonId();
        String param =requestJO.getString("key");
        int page = requestJO.getInteger("page");
        Page<SpBrand> spBrands = null;
        if (StringUtils.isEmpty(requestJO.getString("key"))) {
            spBrands = spBrandRepository.findAllBrandStandard(PageRequest.of(page, 20, Sort.by(Sort.Direction.DESC, "id")));
        } else {
            //所有的品牌件
            spBrands = spBrandRepository.findAllLikeIdAndName(param, PageRequest.of(page, 20, Sort.by(Sort.Direction.DESC, "id")));
        }
        //供应商置顶的品牌
        List<String> topBrandId = firstBrandRepository.findAllBySupplier(personId);
        JSONArray topBrand = new JSONArray();
        if (page == 0) {
            topBrand = new JSONArray();
            if (!topBrandId.isEmpty()) {
                topBrand = JSONArray.parseArray(JSON.toJSONString(MapUtil.mapped(spBrandRepository.findInId(topBrandId))));
                topBrand.forEach(j -> {
                    JSONObject item = (JSONObject) j;
                    item.put("top", true);
                    item.put("qualityName", "置顶");
                    item.put("groupBy", "qualityName");
                });
            }
            if (StringUtils.isEmpty(requestJO.getString("key"))) {
                //除品牌件外的类型
                List<SpBrand> allNotBrandStandard = spBrandRepository.findAllNotBrandStandard();
                JSONArray allNotBrandStandardBrand = JSONArray.parseArray(JSON.toJSONString(MapUtil.mapped(allNotBrandStandard)));
                //排除置顶的品牌
                List<Object> notBrandStandard = allNotBrandStandardBrand.stream().filter(item -> !topBrandId.contains(((JSONObject) item).getString("id"))).collect(toList());//排除置顶的品牌
                topSign(notBrandStandard);
                topBrand.addAll(notBrandStandard);
            }
        }
        //处理品牌件排序
        JSONArray brand = JSONArray.parseArray(JSON.toJSONString(MapUtil.mapped(spBrands.getContent())));
        //前端分组需要的参数
        List<Object> content = brand.stream().filter(item -> !topBrandId.contains(((JSONObject) item).getString("id"))).collect(toList());//排除置顶的品牌
        //前端分组标记
        topSign(content);

        //有序列表排序
        topBrand.addAll(content);

        Collections.reverse(content);
        return MapUtil.mapper("content", topBrand, "size", 20, "page", page, "pages", spBrands.getTotalPages() + topBrand.size(), "total", spBrands.getTotalElements());
    }

    //前端分组标记
    private void topSign(List<Object> content) {
        content.forEach(o -> {
            JSONObject item = (JSONObject) o;
            item.put("groupBy", "qualityName");
            item.put("top", false);
            int month = getMonth(item.getString("qualityId"));
            item.put("ZBQ", month);
        });
    }

    //根据品质获取质保期
    private int getMonth(String qualityId) {
        int month = 12;
        if ("001".equals(qualityId)){
            month = 3;
        }
        if ("004".equals(qualityId)){
            month = 1;
        }
        return month;
    }

    /**
     * 提交
     *
     * @param request
     * @return 提交结果
     */
    public Map submit(SimpleRequest request) {
        JSONObject requestJO = request.getJO();

        //报价单
        Quote quote = quoteRepository.findOne(requestJO.getJSONObject("enquiry").getString("quoteId"));
        PartyRole supplier = getBean(PartyRoleRepository.class).findOne(quote.getPartyRoleId());
        //修改询价单状态
        Enquiry enquiry = enquiryRepository.findOne(requestJO.getJSONObject("enquiry").getString("id"));
        if (enquiry.getExpireDate() <= new Date().getTime()) throw new RuntimeException("报价时间已截止，无法提交报价！");

        enquiryRepository.saveAndFlush(enquiry);

        JSONArray enquiryItems = requestJO.getJSONArray("enquiryItem");
        for (Object o : enquiryItems) {
            JSONObject enquiryItemJson = (JSONObject) o;
            EnquiryItem enquiryItem = enquiryItemRepository.findOne(enquiryItemJson.getString("id"));
            JSONArray pageQuoteResult = enquiryItemJson.getJSONArray("quoteResult");
            distinct(pageQuoteResult, requestJO.getString("sourceType"));//不允许提交重复数据
            //提交报价结果和生成临时商品
            createQuoteResultAndProduct(quote, supplier, enquiry, enquiryItem, pageQuoteResult, requestJO.getString("sourceType"));
            //更新报价配件状态和报价状态
            updateState(quote, supplier, enquiryItem);

        }

        return MapUtil.mapper("enquiryItem", enquiryItems, "page", requestJO.getString("page"), "size", requestJO.getString("size"));
    }

    //更新询价状态和报价状态
    private void updateState(Quote quote, PartyRole supplier, EnquiryItem enquiryItem) {
        //报价配件状态
        List<QuoteItem> quoteIdAndSupplier = quoteItemRepository.findQuoteIdAndSupplierAndCategory(supplier.getId(), enquiryItem.getId(), quote.getId());
        if (quoteIdAndSupplier.size() != 0) {
            QuoteItem quoteItem = quoteIdAndSupplier.stream().findFirst().get();
            quoteItem.setQuoteState("already");
            quoteItemRepository.saveAndFlush(quoteItem);
        }
        //报价单状态
        List<QuoteItem> quoteItems = quoteItemRepository.findQuoteIdAndSupplier(supplier.getId(), quote.getId());
        List<QuoteItem> collectQuoteItem = quoteItems.stream().filter(quoteItem -> "already".equals(quoteItem.getQuoteState())).collect(toList());
        if (quoteItems.size() == collectQuoteItem.size()) {
            quote.setState("finish");
            quoteRepository.saveAndFlush(quote);
        }
        //询价单状态
        Enquiry enquiry = enquiryRepository.findOne(quote.getEnquiryId());
        List<Quote> quotes = quoteRepository.findEnquiryIds(Arrays.asList(enquiry.getId()));
        List<Quote> filterQuotes = quotes.stream().filter(quoteItem -> "finish".equals(quoteItem.getState())).collect(toList());
        if (filterQuotes.size() >= 3) {
            enquiry.setState("finish");
        }

        enquiryRepository.saveAndFlush(enquiry);
    }

    //提交报价结果和生成临时商品(商品不存在才生成临时商品)
    private void createQuoteResultAndProduct(Quote quote, PartyRole supplier, Enquiry enquiry, EnquiryItem enquiryItem, JSONArray pageQuoteResult, String type) {
        List<Object> filterResult = pageQuoteResult.stream().filter(item -> StringUtils.isEmpty(((JSONObject) item).getString("systemSign"))).collect(toList());
        List<QuoteItem> quoteItems = quoteItemRepository.findQuoteIdAndSupplierAndCategory(supplier.getId(), enquiryItem.getId(), quote.getId());
        if (quoteItems.isEmpty()) throw new RuntimeException("报价配件不存在！");
        QuoteItem quoteItem = quoteItems.stream().findFirst().get();
        for (Object s : filterResult) {
            JSONObject quoteResultJson = (JSONObject) s;
            //校验数据
            boolean valid = isValid(type, quoteResultJson);
            if (valid) {
                //构建报价结果
                QuoteResult quoteResult = newQuoteResult(enquiry, quoteResultJson, enquiryItem, quote, quoteItem);

                //是否存在该商品
                SpProduct spProduct = isProduct(quoteResultJson, supplier, enquiry, enquiryItem, type);
                if (Objects.isNull(spProduct)) {
                    //创建临时商品
                    spProduct = newProduct(supplier, quoteResultJson, enquiryItem, type,enquiry);
                    //记录历史报价
                    newFirsBrand(spProduct);
                    quoteResult.setProduct(spProduct);
                } else {
                    //是否存在临时商品
                    if (spProduct.getTemporary()) {
                        spProduct.setNotTaxUnitPrice(quoteResultJson.getDouble("notTaxUnitPrice"));
                        spProductRepository.saveAndFlush(spProduct);
                    }
                    quoteResult.setProduct(spProduct);
                }
                quoteResultRepository.saveAndFlush(quoteResult);

            }else {
                quoteItem.setQuoteState("lack");
                quoteItemRepository.saveAndFlush(quoteItem);
            }
        }
    }

    private SpProduct isProduct(JSONObject quoteResultJson, PartyRole supplier, Enquiry enquiry, EnquiryItem enquiryItem, String type){
        if ("tyre".equals(type)){
            String brandName = quoteResultJson.getJSONObject("quoteBrand").getString("name");//品牌
            String figure = quoteResultJson.getString("figure");//花纹
            String loadIndex = quoteResultJson.getString("loadIndex");//载重指数
            String speedClass = quoteResultJson.getString("speedClass");//速度等级
            Boolean antiExplosion = quoteResultJson.getBoolean("antiExplosion");//防爆
            String specification = quoteResultJson.getString("specification");//规格尺寸
            TyreProduct tyreProduct = getBean(TyreProductRepository.class).findByAllConditionSupplier(brandName, figure, loadIndex, speedClass, antiExplosion, specification, supplier.getId());
            if (Objects.isNull(tyreProduct)) return null;
            return tyreProduct.getSpProduct();
        }
        //精品改装临时商品
        if ("refit".equals(type)){
            SpBrand spBrand = spBrandRepository.findByName(quoteResultJson.getJSONObject("quoteBrand").getString("name"));
            List<SpProduct> spProducts = spProductRepository.findOneByBrandAndSupplier(quoteResultJson.getJSONObject("quoteOE").getString("id"),
                    spBrand.getId(), supplier.getId(), quoteResultJson.getJSONObject("quoteOE").getString("name"));
            if (spProducts.size() != 1) return null;
            return spProducts.stream().findFirst().get();
        }
        String formatOE = optimizeOE(quoteResultJson.getJSONObject("quoteOE").getString("OE"), enquiry);
        List<SpProduct> spProducts = spProductRepository.findOneByBrandAndSupplier(formatOE,
                quoteResultJson.getJSONObject("quoteBrand").getString("id"), supplier.getId(), enquiryItem.getCategory().getName());
        if (spProducts.size() != 1) return null;
        return spProducts.stream().findFirst().get();
    }

    //校验数据是否有效
    private boolean isValid(String type, JSONObject quoteResultJson) {
        boolean valid = Objects.nonNull(quoteResultJson.getJSONObject("quoteOE")) && Objects.nonNull(quoteResultJson.get("quoteBrand"))
                && Objects.nonNull(quoteResultJson.get("notTaxUnitPrice")) && Objects.nonNull(quoteResultJson.get("placeOfDispatch"))
                && StringUtils.isNotEmpty(quoteResultJson.getJSONObject("quoteBrand").getString("id"));
        if ("tyre".equals(type)){
            valid = StringUtils.isNotEmpty(quoteResultJson.getString("quoteBrand")) && StringUtils.isNotEmpty(quoteResultJson.getString("figure")) &&
                    StringUtils.isNotEmpty(quoteResultJson.getString("loadIndex")) && StringUtils.isNotEmpty(quoteResultJson.getString("speedClass")) &&
                    StringUtils.isNotEmpty(quoteResultJson.getString("antiExplosion")) && StringUtils.isNotEmpty(quoteResultJson.getString("notTaxUnitPrice")) &&
                    StringUtils.isNotEmpty(quoteResultJson.getString("specification"));
        }
        if ("refit".equals(type)){
            valid = Objects.nonNull(quoteResultJson.get("quoteBrand")) && Objects.nonNull(quoteResultJson.get("notTaxUnitPrice")) && Objects.nonNull(quoteResultJson.getJSONObject("quoteOE"))
                    && Objects.nonNull(quoteResultJson.get("placeOfDispatch")) && StringUtils.isNotEmpty(quoteResultJson.getJSONObject("quoteOE").getString("id"));
        }
        return valid;
    }

    //禁止报价同样的商品
    private void distinct(JSONArray pageQuoteResult, String type) {
        Set<String> set = new HashSet();
        if ("tyre".equals(type)){
            pageQuoteResult.forEach(o -> {
                JSONObject quoteResult = (JSONObject) o;
                if (!set.add(quoteResult.getString("specification") + quoteResult.getJSONObject("quoteBrand").getString("name") + quoteResult.getString("figure") + quoteResult.getString("loadIndex")
                        + quoteResult.getString("speedClass") + quoteResult.getString("antiExplosion") + quoteResult.getString("notTaxUnitPrice"))) {
                    throw new RuntimeException("当前页面存在相同的报价商品，请检查后重试！");
                }
            });
            return;
        }
        if ("refit".equals(type)){
            pageQuoteResult.forEach(o -> {
                JSONObject quoteResult = (JSONObject) o;
                if (!set.add(quoteResult.getJSONObject("quoteOE").getString("name")))
                    throw new RuntimeException("当前页面存在相同的报价商品，请检查后重试！");
            });
            return;
        }
        pageQuoteResult.forEach(o -> {
            JSONObject quoteResult = (JSONObject) o;
            if (!set.add(quoteResult.getJSONObject("quoteOE").getString("OE") + quoteResult.getJSONObject("quoteBrand").getString("id")))
                throw new RuntimeException("当前页面存在相同的报价商品，请检查后重试！");
        });
    }

    /**
     * 记录历史报价
     *
     * @param spProduct
     */
    private void newFirsBrand(SpProduct spProduct) {
        FirstBrand firstBrand = new FirstBrand();
        firstBrand.setOE(spProduct.getOE());
        firstBrand.setProductId(spProduct.getId());
        firstBrand.setPartyRoleId(spProduct.getSupplier().getId());
        firstBrandRepository.saveAndFlush(firstBrand);
    }

    /**
     * 构建临时商品
     *
     * @param supplier
     * @param quoteResult
     * @return
     */
    private SpProduct newProduct(PartyRole supplier, JSONObject quoteResult, EnquiryItem enquiryItem, String type, Enquiry enquiry) {
        SpProduct product = new SpProduct();
        product.setSupplier(supplier);
        product.setNotTaxUnitPrice(quoteResult.getDouble("notTaxUnitPrice"));
        product.setPutawayState(false);
        product.setTemporary(true);
        product.setProductState("history");
        product.setMateState("notNeed");
        //轮胎临时商品
        if ("tyre".equals(type)){
            return newTyreProduct(product, quoteResult);
        }
        //精品改装临时商品
        if ("refit".equals(type)){
            return newRefitProduct(product, quoteResult);
        }

        //全车件
        product.setName(Objects.isNull(enquiryItem.getCategory()) ? "待编译" : enquiryItem.getCategory().getName());
        //校验零件号是否符合规范
        String OE = optimizeOE(quoteResult.getJSONObject("quoteOE").getString("OE"),enquiry);
        product.setOE(OE);
        product.setSpBrand(spBrandRepository.findOne(quoteResult.getJSONObject("quoteBrand").getString("id")));
        product.setStandardType("brandWhole");
        product.setType("全车件");

        return spProductRepository.saveAndFlush(product);
    }

    //精品改装临时商品
    private SpProduct newRefitProduct(SpProduct product, JSONObject quoteResult){
        product.setName(quoteResult.getJSONObject("quoteOE").getString("name"));
        //校验零件号是否符合规范
        product.setOE(quoteResult.getJSONObject("quoteOE").getString("id"));
        product.setSpBrand(spBrandRepository.findByName(quoteResult.getJSONObject("quoteBrand").getString("name")));
        product.setStandardType("refit");
        product.setType("精品改装");
        return spProductRepository.saveAndFlush(product);
    }

    //创建轮胎询价商品
    private SpProduct newTyreProduct(SpProduct product, JSONObject quoteResult){
        product.setOE(quoteResult.getString("specification"));
        String brandName = StringUtils.isEmpty(quoteResult.getString("brand")) ? quoteResult.getJSONObject("quoteBrand").getString("name") :
                quoteResult.getString("brand");
        product.setSpBrand(spBrandRepository.findByName(brandName));
        product.setStandardType("Tyre");
        product.setType("轮胎");
        String name = brandName + "轮胎" + quoteResult.getString("specification") + "(花纹" + quoteResult.getString("figure") + ")" +
                (quoteResult.getBoolean("antiExplosion") ? "防爆" : "") + "/" + quoteResult.getString("loadIndex") + quoteResult.getString("speedClass");
        product.setName(name.toUpperCase());
        SpProduct spProduct = spProductRepository.saveAndFlush(product);
        TyreProduct tyreProduct = new TyreProduct();
        tyreProduct.setFigure(quoteResult.getString("figure"));
        tyreProduct.setSpecification(quoteResult.getString("specification"));
        tyreProduct.setLoadIndex(quoteResult.getString("loadIndex"));
        tyreProduct.setSpeedClass(quoteResult.getString("speedClass"));
        tyreProduct.setAntiExplosion(quoteResult.getBoolean("antiExplosion"));
        tyreProduct.setSpProduct(spProduct);
        getBean(TyreProductRepository.class).saveAndFlush(tyreProduct);
        return spProduct;
    }

    /**
     * 零件号乱码校验
     * @param OE 输入零件号
     * @param enquiry 询价单
     * @return
     */
    public String optimizeOE(String  OE,Enquiry enquiry){
        String PN = OE;
        OE = OE.replace("-","").replace("/", "").replace("，", "").replace("   ", "")
                .replace(" ", "").replace(" ", "").replace("。", "").replace(",", "")
                .replace(";", "").replace("\\*", "").replace("……", "").replace("\t", "")
                .replace("！", "").replace("!", "").replace("；","")
                .replace(".", "").replace("、", "").toUpperCase();
        if (OE.length() < 4 || judgeContinueLJID(OE) == false) {
            JSONObject response = JSONObject.parseObject(invoke("fn.api.getCustomerCarDetailInfoNotSession", MapUtil.mapped(enquiry)).toString());
           JSONObject jsonObject =  response.getJSONObject("body");
            OE = jsonObject.getJSONObject("carBaseInfo").getString("partsCode");
           List<SpProduct> spProducts =  spProductRepository.findByOEAndTemporary(OE);
           if (spProducts.size()>0) throw  new RuntimeException(PN+" 零件号输入不符合规范");
        }
        return OE.toUpperCase();
    }

    /**
     * 判断零件编码是否连续
     * @param vLJID
     * @return
     */
    private boolean judgeContinueLJID(String vLJID) {
        // 判断是否相同，例如：11111
        boolean flag = true;

        //判断是否连续
        String copyLJID = vLJID;
        String letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String letter2 = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
        String number = "012345678910";
        String number2 = "109876543210";
        if (letter.indexOf(copyLJID) != -1 || letter2.indexOf(copyLJID) != -1) {
            return flag = false;
        } else if (number.indexOf(copyLJID) != -1 || number2.indexOf(copyLJID) != -1) {
            return flag = false;
        }

        int count = 1;
        char[] copyLJID_Array = vLJID.toCharArray();
        int copyLJID_Len = copyLJID_Array.length;
        for (int i = 0; i < copyLJID_Len - 1; i++) {
            int icount = i+1;
            if (copyLJID_Array[i] == copyLJID_Array[icount]) {
                count++;
            }
        }
        if (copyLJID_Len == count) {
            return flag = false;
        }

        return flag;
    }

    /**
     * 构建报价结果
     *
     * @param enquiry 询价单
     * @param json    页面数据
     */
    private QuoteResult newQuoteResult(Enquiry enquiry, JSONObject json, EnquiryItem enquiryItem, Quote quote, QuoteItem quoteItem) {
        QuoteResult quoteResult = new QuoteResult();
        if (StringUtils.isNotEmpty(json.getString("id"))){
            quoteResult = quoteResultRepository.findOne(json.getString("id"));
        }
        quoteResult.setEnquiryId(enquiry.getId());
        quoteResult.setQuoteId(quote.getId());
        quoteResult.setSupplierId(quote.getPartyRoleId());
        quoteResult.setEnquiryItem(enquiryItem.getId());
        quoteResult.setQuoteItem(quoteItem.getId());

        String brand = "";
        if (StringUtils.isNotEmpty(json.getString("quoteBrand"))){
            brand = json.getJSONObject("quoteBrand").getString("name");
        }

        quoteResult.setQuoteBrand(spBrandRepository.findByName(brand));
        quoteResult.setNotTaxUnitPrice(json.getDouble("notTaxUnitPrice"));
        //获取票点
        if (enquiry.getBeInvoice()) {
            String result = (String) invoke("fn.fnEnquiryService.getSupplierTicketPoint", MapUtil.mapper("store", enquiry.getStore(),
                    "supplierId", quote.getPartyRoleId(), "brand", brand));
            JSONObject body = JSONObject.parseObject(result);
            DecimalFormat df = new DecimalFormat("#.00");//保留小数点后两位
            double taxUnitPrice = quoteResult.getNotTaxUnitPrice() * (body.getDoubleValue("body") / 100 + 1.0);//计算含税单价
            //含税单价
            quoteResult.setTaxUnitPrice(Double.parseDouble(df.format(taxUnitPrice)));
        } else {
            quoteResult.setTaxUnitPrice(json.getDouble("notTaxUnitPrice"));
        }

        quoteResult.setPlaceOfDispatch(json.getInteger("placeOfDispatch"));
        quoteResult.setState(quoteResult.getPlaceOfDispatch() == 0 ? "10" : "00");
        quoteResult.setNote(json.getString("note"));
        quoteResult.setPng(json.getString("png"));
        quoteResult.setZBQ(json.getInteger("ZBQ"));
        quoteResult.setQuotaValid(1);
        return quoteResultRepository.save(quoteResult);
    }

    /**
     * 查询询价单列表
     *
     * @param request
     * @return 询价单列表
     */
    public Map findAllEnquiries(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        PartyRole supplier = request.getPerson();
        //准备数据
        String id = "".equals(requestJO.getString("enquiryId")) ? null : requestJO.getString("enquiryId");
        String supplierId = "".equals(requestJO.getString("supplierId")) ? null : requestJO.getString("supplierId");
        JSONArray createDateJson = requestJO.getJSONArray("createDate");
        Date startDate = null;
        Date finishDate = null;
        //处理时间格式
        if (Objects.nonNull(createDateJson)) {
            for (int i = 0; i < createDateJson.size(); i++) {
                if (i == 0) {
                    String starts = (String) createDateJson.get(i);
                    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        startDate = ft.parse(starts);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                }
                if (i == 1) {
                    String starts = (String) createDateJson.get(i);
                    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        finishDate = ft.parse(starts);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        JSONArray condition = requestJO.getJSONArray("condition");
        List<Object> suppliers = null;
        if (Objects.nonNull(condition)) {
            for (Object o : condition) {
                if (o instanceof HashMap){
                    HashMap<String, Object> item = (HashMap) o;
                    if ("supplier".equals(item.get("field")) && StringUtils.isNotEmpty(item.get("value")+"")) {
                        List value = (List) item.get("value");
                        suppliers = (List<Object>) value.stream().distinct().collect(toList());
                    }
                } else {
                    JSONObject item = (JSONObject) o;
                    if ("supplierId".equals(item.getString("field"))) {
                        String value = item.getString("value");
                        if (StringUtils.isNotEmpty(value)){
                            suppliers = Arrays.asList(value);
                        }

                    }
                }
            }
        }
        String state = "".equals(requestJO.getString("state")) ? null : requestJO.getString("state");
        Boolean beInvoice = "".equals(requestJO.getString("beInvoice")) ? null : requestJO.getBoolean("beInvoice");
        String servicePlanId = "".equals(requestJO.getString("servicePlanId")) ? null : requestJO.getString("servicePlanId");
        String carLicense = "".equals(requestJO.getString("carLicense")) ? null : requestJO.getString("carLicense");
        String vin = "".equals(requestJO.getString("vin")) ? null : requestJO.getString("vin");
        String type = "".equals(requestJO.getString("type")) ? null : requestJO.getString("type");
        List<String> offerlist = null;
        if(requestJO.getJSONObject("offerGroup")!=null){
            JSONObject jsonObject = JSON.parseObject(invoke("cm.deptOfferGroupService.fiindAllName", MapUtil.mapper("name", requestJO.getJSONObject("offerGroup").getString("name"))));
            JSONArray array = jsonObject.getJSONArray("body");
            String js = JSONObject.toJSONString(array, SerializerFeature.WriteClassName);
            offerlist = JSONObject.parseArray(js,String.class);
            if(offerlist.size()==0)offerlist=null;
        }
        int page = requestJO.getIntValue("page");
        //开始查询
        //超级管理员直接查
        /*if ("yyadmin".equals(supplier.getId())) {
            return getEnquiries(id, startDate, finishDate, state, beInvoice, page);
        }*/
        //询价单id查询
        if (StringUtils.isNotEmpty(id) && id.startsWith("XJ")) {
            return getEnquiryList(suppliers, id, startDate, finishDate, state, beInvoice, page,supplierId,servicePlanId,carLicense,offerlist, requestJO,vin,type);
        }
        //根据 来源单号 车牌号查询
        if (servicePlanId!=null || carLicense!=null || vin!=null || (type!=null && offerlist==null)) {
            return getServicePlanIdAndCarLicense(suppliers, id, startDate, finishDate, state, beInvoice, page,supplierId,servicePlanId,carLicense,offerlist, requestJO,vin,type);
        }
        Page<Quote> quotes;
        List<String> distinctQuoteId;
        if( offerlist != null){
            List<Enquiry> enquiryList = enquiryRepository.findAll(JpaDsl.toCriteriaIgnoreNull("store","IN",offerlist,"type","EQ",type),Sort.by(Sort.Direction.DESC, "id"));
            List<String> enquiryidList = enquiryList.stream().map(Enquiry::getId).distinct().collect(toList());
            if(enquiryidList.size()==0) return requestJO;
            enquiryidList = enquiryidList.stream().limit(1000).distinct().collect(toList());
            quotes = quoteRepository.findAll(JpaDsl.toCriteriaIgnoreNull("id", "EQ", id, "createDate", "LTE", finishDate,"enquiryId","IN",enquiryidList,
                    "createDate", "GTE", startDate,"state", "EQ", state, "partyRoleId", "IN", suppliers),PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
             distinctQuoteId = quotes.getContent().stream().map(Quote::getEnquiryId).distinct().collect(toList());
            if(distinctQuoteId.size()==0)distinctQuoteId=null;
            List<Enquiry> enquiries = enquiryRepository.findAll(JpaDsl.toCriteriaIgnoreNull("id", "IN", distinctQuoteId));
            //询价单带上报价单
            List list = setQuote(quotes.getContent(), enquiries,supplierId);

            requestJO.putAll(MapUtil.mapper("content", list, "page", page, "sum", quotes.getTotalPages()));
            return requestJO;
        }
        //报价单id查询
         quotes = quoteRepository.findAll(JpaDsl.toCriteriaIgnoreNull("id", "EQ", id, "createDate", "LTE", finishDate,
                "createDate", "GTE", startDate,"state", "EQ", state, "partyRoleId", "IN", suppliers),
                PageRequest.of(page, 50, Sort.by(Sort.Direction.DESC, "id")));
        if (quotes.isEmpty()) {
            return requestJO;
        }
         distinctQuoteId = quotes.getContent().stream().map(Quote::getEnquiryId).distinct().collect(toList());

        List<Enquiry> enquiries = enquiryRepository.findAll(JpaDsl.toCriteriaIgnoreNull("id", "IN", distinctQuoteId,"type","EQ",type,"beInvoice","EQ",beInvoice));
        //询价单带上报价单
        List list = setQuote(quotes.getContent(), enquiries,supplierId);
        requestJO.putAll(MapUtil.mapper("content", list, "page", page, "sum", quotes.getTotalPages()));
        return requestJO;

    }

    //询价单id查询
    private Map getEnquiryList(List suppliers, String id, Date startDate, Date finishDate, String state, Boolean beInvoice,
                               int page,String supplierId,String servicePlanId,String carLicense,List<String> offerlist, JSONObject requestJO,String vin,String type) {
        List<Quote> oneBySupplier = null;
        if(StringUtils.isNotEmpty(id) && id.startsWith("XJ")){
            oneBySupplier = quoteRepository.findAll(JpaDsl.toCriteriaIgnoreNull("enquiryId", "EQ", id, "partyRoleId", "IN", suppliers,
                    "createDate", "LTE", finishDate,
                    "createDate", "GTE", startDate,
                    "state", "EQ", state,
                    "beInvoice", "EQ", beInvoice));
        }

        if (oneBySupplier.isEmpty()) return requestJO;
        List<Enquiry> enquiries = enquiryRepository.findAll(JpaDsl.toCriteriaIgnoreNull("id", "EQ",id,
                "servicePlanId","EQ",servicePlanId,
                "carLicense","EQ",carLicense,
                "vin","EQ",vin,
                "type","EQ",type,
                "store","IN",offerlist), Sort.by(Sort.Direction.DESC, "id"));

        List list = setQuote(oneBySupplier, enquiries,supplierId);
        requestJO.putAll(MapUtil.mapper("content", list, "page", page, "sum", 1));
        return requestJO;
    }

    //根据 来源单号 车牌号查询
    private Map getServicePlanIdAndCarLicense(List suppliers, String id, Date startDate, Date finishDate, String state, Boolean beInvoice,
                                              int page,String supplierId,String servicePlanId,String carLicense,List<String> offerlist, JSONObject requestJO,String vin,String type) {
        List<Enquiry> enquiries = new ArrayList<>();
        List<Quote> oneBySupplier = new ArrayList<>();
       int firstIndex=(page)*50;
       if(page==0)firstIndex=0;
        if(StringUtils.isEmpty(id) || id.startsWith("XJ")){
                enquiries =  enquiryRepository.findAll(JpaDsl.toCriteriaIgnoreNull("id", "EQ",id,
                    "servicePlanId","EQ",servicePlanId,
                    "carLicense","EQ",carLicense,
                    "createDate", "LTE", finishDate,
                    "createDate", "GTE", startDate,
                    "beInvoice", "EQ", beInvoice,
                    "vin","EQ",vin,
                    "type","EQ",type,
                    "store","IN",offerlist), Sort.by(Sort.Direction.DESC, "id"));
            if (enquiries.isEmpty()) return requestJO;
                List<String> enquiryIdList = enquiries.stream().map(item -> item.getId()).collect(toList());
                enquiryIdList = enquiryIdList.stream().limit(1000).distinct().collect(toList());
                oneBySupplier = quoteRepository.findAll(JpaDsl.toCriteriaIgnoreNull("enquiryId", "IN", enquiryIdList, "partyRoleId", "IN", suppliers,
                        "createDate", "LTE", finishDate,
                        "createDate", "GTE", startDate,
                        "state", "EQ", state));

        }else{
            oneBySupplier = quoteRepository.findAll(JpaDsl.toCriteriaIgnoreNull("id", "EQ", id, "partyRoleId", "IN", suppliers,
                    "createDate", "LTE", finishDate,
                    "createDate", "GTE", startDate,
                    "state", "EQ", state,
                    "beInvoice", "EQ", beInvoice));
            if (oneBySupplier.isEmpty()) return requestJO;
            enquiries =  enquiryRepository.findAll(JpaDsl.toCriteriaIgnoreNull("servicePlanId","EQ",servicePlanId, "carLicense","EQ",carLicense,"store","IN",offerlist), Sort.by(Sort.Direction.DESC, "id"));
            if (enquiries.isEmpty())return requestJO;
        }



        List list = setQuote(oneBySupplier, enquiries,supplierId);
        requestJO.putAll(MapUtil.mapper("content", list.stream().skip(firstIndex).limit(50).collect(toList()), "page", page, "sum", list.size()==0?1:Math.ceil(list.size()/50.00)));
        return requestJO;
    }

    //超级管理员直接查
    private Map getEnquiries(String id, Date startDate, Date finishDate, String state, Boolean beInvoice, int page,String supplierId) {
        Page<Enquiry> enquiries = enquiryRepository.findAll(JpaDsl.toCriteriaIgnoreNull("id", "EQ", id,
                "createDate", "LTE", finishDate,
                "createDate", "GTE", startDate,
                "state", "EQ", state,
                "beInvoice", "EQ", beInvoice), PageRequest.of(page, 10, Sort.by(Sort.Direction.DESC, "id")));
        //根据询价单号查询所有报价单
        List<String> enquiryIds = enquiries.getContent().stream().map(Enquiry::getId).collect(toList());
        if (enquiryIds.isEmpty()) throw new RuntimeException("暂无单据！");
        List<Quote> quotes = quoteRepository.findEnquiryIds(enquiryIds);

        if (!StringUtils.isEmpty(supplierId)){
            quotes = quotes.stream().filter(f -> supplierId.equals(f.getPartyRoleId())).collect(Collectors.toList());
        }
        //根据报价单生成查询结果
        List<Enquiry> content = quotes.stream().map(quote -> {
            Enquiry thisEnquiry = enquiries.getContent().stream().filter(enquiry -> quote.getEnquiryId().equals(enquiry.getId())).collect(toList()).stream().findFirst().get();
            Enquiry enquiry = new Enquiry();
            BeanUtils.copyProperties(thisEnquiry, enquiry);//浅拷贝，仅复制值不传递内存地址。
            enquiry.setQuoteId(quote.getId());
            enquiry.setSum(quoteItemRepository.findAllQuoteId(quote.getId()).size());
            PartyRole partyRole = roleRepository.findOne(quote.getPartyRoleId());
            if (!ObjectUtils.isEmpty(partyRole)) {
                enquiry.setSupplierName(partyRole.getName());
            }
            return enquiry;
        }).collect(toList());
        return MapUtil.mapper("content", content, "page", page, "sum", enquiries.getTotalPages());
    }

    //询价单带上报价单
    private List setQuote(List<Quote> quotes, List<Enquiry> enquiries,String supplierId) {
        List<Enquiry> result = new ArrayList<>();
        if (StringUtils.isNotEmpty(supplierId)){
            quotes = quotes.stream().filter(f -> supplierId.equals(f.getPartyRoleId())).collect(Collectors.toList());
        }
        quotes.forEach(quote -> {

            List<Enquiry> enquiryList = enquiries.stream().filter(enquiry -> enquiry.getId().equals(quote.getEnquiryId())).collect(toList());
            if(enquiryList.size()==0){return;}
            Enquiry thisEnquiry  =  enquiryList.stream().findFirst().get();
            Enquiry enquiry = new Enquiry();
            BeanUtils.copyProperties(thisEnquiry, enquiry);//浅拷贝，仅复制值不传递内存地址。
            enquiry.setQuoteId(quote.getId());
            enquiry.setState(quote.getState());
            enquiry.setSum(quoteItemRepository.findAllQuoteId(quote.getId()).size());
            PartyRole partyRole = roleRepository.findOne(quote.getPartyRoleId());
            if (!ObjectUtils.isEmpty(partyRole)) {
                enquiry.setSupplierId(quote.getPartyRoleId());
                enquiry.setSupplierName(partyRole.getName());
            }
            result.add(enquiry);
        });
        result.stream().forEach(e ->{
            JSONObject jsonObject = JSON.parseObject(invoke("cm.deptOfferGroupService.findByDeptId", MapUtil.mapper("deptId",e.getStore())));
            if(jsonObject.getString("body")!=null){
                e.setOfferGroup(jsonObject.getJSONObject("body").getString("name"));
            }
        });
        return result;
    }

    //更新询价单状态
    public void enquiryState(SimpleRequest request) {
        List<Quote> quotes = quoteRepository.findAll(JpaDsl.toCriteriaByEq("state", "ing"));
        quotes.forEach(quote ->{
            Enquiry enquiry = enquiryRepository.findOne(quote.getEnquiryId());
            long time = new Date().getTime();
            long expireDate = enquiry.getExpireDate();
            if (time >= expireDate) {
                if ("ing".equals(enquiry.getState())){
                    enquiry.setState("expired");
                    enquiryRepository.saveAndFlush(enquiry);
                }
                quote.setState("expired");
                quoteRepository.saveAndFlush(quote);
            }
        });
    }

    /**
     * 品牌置顶
     *
     * @param request
     */
    public boolean topOf(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        Boolean top = requestJO.getJSONObject("SpBrand").getBoolean("top");
        String brand = requestJO.getJSONObject("SpBrand").getString("id");
        PartyRole partyRole = request.getPerson();
        if (top) {
            List<FirstBrand> brandAndSupplier = firstBrandRepository.findBrandAndSupplier(brand, partyRole.getId());
            FirstBrand firstBrand = brandAndSupplier.stream().findFirst().get();
            firstBrandRepository.delete(firstBrand);
        } else {
            FirstBrand firstBrand = new FirstBrand();
            firstBrand.setBrandId(brand);
            firstBrand.setPartyRoleId(partyRole.getId());
            firstBrandRepository.saveAndFlush(firstBrand);
        }
        return true;
    }

    /**
     * 询价单倒计时结束
     *
     * @param request
     */
    public void expire(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        String id = requestJO.getString("id");
    }

    /**
     * 获取供应商办公地址
     *
     * @param supplierId
     * @return
     */
    public String acquireAddress(String supplierId) {
        PartyRole partyRole = getBean(PartyRoleRepository.class).findOne(supplierId);
        return partyRole.getParty().getCorporate().getOfficeCity().getName();
    }

    /**
     * 获取客户车辆信息
     * @param request
     * @return
     */
    public JSONObject queryCustomer(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        JSONObject param = requestJO.getJSONObject("conditionModel");
        JSONObject response = JSONObject.parseObject(invoke("fn.api.getCustomerCarDetailInfoNotSession", param).toString());
        return response.getJSONObject("body");
    }

    /**
     * 查询车型信息
     * @param request
     * @return
     */
    public JSONObject findMotorcycleType(SimpleRequest request){
        JSONObject requestJO = request.getJO().getJSONObject("conditionModel").getJSONObject("enquiry");
        JSONObject response = JSONObject.parseObject(invoke("fn.api.getCustomerCarDetailInfoNotSession", requestJO).toString());
        return response.getJSONObject("body");
    }

    public boolean quoteYesOrNO(SimpleRequest request){
        return false;
    }

    /**
     * 报价监控
     * @param request
     * @return
     */
    public Map findOfferPage(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject jsonObject =  (JSONObject) enquiryDao.countOffer(jo).get(0);
        Integer count = jsonObject.getInteger("COUNT");
        Integer page = jo.getInteger("page");
        Integer size = jo.getInteger("size");
        if(size>count){
            size = count;
            page = count-50;
        }
        if(page<0){
            page=0;
            size=50;
        }
        JSONArray array = enquiryDao.findAllOfferPage(jo,page,size);
        return  MapUtil.mapper("content", array, "page", page, "size",size,"sum",count,"model",request.getJO().getString("model"));

    }

    /**
     * 测试方法
     * @param request
     * @return
     */
    public JSONObject test(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        return JSONObject.parseObject(invoke("fn.api.getCustomerCarDetailInfo", requestJO).toString());
    }

    @FuncAlias(name = "按单号获取供应商用户")
    public List<String> findByQuoteEnquiryId(String id) {
        try {
            List<String> byEnquiryId = quoteRepository.findByEnquiryId(id);
            if (byEnquiryId.isEmpty())return null;
            return  getBean(UserRepository.class).findAllByListSupplier(byEnquiryId).stream().map(userId -> String.valueOf(userId.toString())).collect(toList());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 询价结果列表查询
     * @param request
     */
    public JSONObject findEnquiryResult(SimpleRequest request){
        JSONObject response = new JSONObject();
        JSONObject requestJO = request.getJO();
        JSONObject jsonObject = packagingData(requestJO);
        List<String> offerlist = null;
        if(jsonObject.get("offerGroup")!=null){
            JSONObject offerGroupJSON = JSON.parseObject(invoke("cm.deptOfferGroupService.fiindByOfferGroup", MapUtil.mapper("offerGroup", jsonObject.get("offerGroup"))));
            JSONArray array = offerGroupJSON.getJSONArray("body");
            String js = JSONObject.toJSONString(array, SerializerFeature.WriteClassName);
            offerlist = JSONObject.parseArray(js,String.class);
            offerlist.add("AAA");
        }
        Page<Enquiry> enquiries = enquiryRepository.findAll(JpaDsl.toCriteriaIgnoreNull(
                "id", "EQ", jsonObject.get("ID"),
                "store", "LIKE", jsonObject.get("STORE"),
                "servicePlanId", "EQ", jsonObject.get("servicePlanId"),
                "store", "IN", offerlist,
                "carLicense", "EQ", jsonObject.get("CAR_LICENSE"),
                "vin", "EQ", jsonObject.get("VIN"),
                "state", "EQ", jsonObject.get("STATUS"),
                "contacts", "EQ", jsonObject.get("CONTACT"),
                "ENQUIRY_GROUP", "EQ", jsonObject.get("ENQUIRY_GROUP"),
                "store", "IN", jsonObject.get("store") == null ? null:jsonObject.getJSONArray("store"),
                "createDate", "GTE", jsonObject.get("CREATE_BIGEND_START") == null ? null : jsonObject.getDate("CREATE_BIGEND_START"),
                "createDate", "LTE", jsonObject.get("CREATE_BIGEND_END") == null ? null : jsonObject.getDate("CREATE_BIGEND_END")), PageRequest.of(requestJO.getInteger("page"), requestJO.getInteger("size"), Sort.by(Sort.Direction.DESC, "createDate")));

        List<Enquiry> enquiryList = enquiries.getContent();
        JSONArray jsonArray = packagingResultData(enquiryList);
        response.put("total", enquiries.getTotalElements());
        response.put("pages", 1);
        response.put("size", jsonArray.size());
        response.put("elements", jsonArray.size());
        response.put("content", jsonArray);
        return response;
    }

    /**
     * 询价结果页面供应商报价弹窗
     * @param request
     * @return
     */
    public JSONObject quoteInfo(SimpleRequest request){
        JSONObject response = new JSONObject();
        JSONObject jo = request.getJO();
        JSONObject data = (JSONObject) jo.get("data");
        JSONObject node = (JSONObject) data.get("node");
        String id = node.getString("id");
        List<Quote> quotes = quoteRepository.findAllByEnquiryId(id);
        JSONArray jsonArray = new JSONArray();
        if (!CollectionUtils.isEmpty(quotes)){
            quotes.forEach(item -> {
                JSONObject js = new JSONObject();
                String partyRoleId = item.getPartyRoleId();
                PartyRole partyRole = partyRoleRepository.findOne(partyRoleId);
                if (!ObjectUtils.isEmpty(partyRole)){
                    js.put("supplierName",partyRole.getParty().getAbbreviation());
                }
                List<QuoteItem> quoteItems = quoteItemRepository.findAllQuote(item.getId());
                double already = 0;
                if (!CollectionUtils.isEmpty(quoteItems)){
                    already = (double) quoteItems.stream().filter(f -> "already".equals(f.getQuoteState())).count();
                }
                js.put("returnRate",already == 0 ? 0+"%":String.format("%.2f", already/quoteItems.size()*100)+"%");
                js.put("state",already == 0 ? "未报价":"已报价");
                jsonArray.add(js);
            });
        }
        response.put("total", jsonArray.size());
        response.put("pages", 1);
        response.put("size", jsonArray.size());
        response.put("elements", jsonArray.size());
        response.put("content", jsonArray);
        return response;
    }

    /**
     * 封装返回数据
     * @param enquiryList
     * @return
     */
    private JSONArray packagingResultData(List<Enquiry> enquiryList){
        JSONArray jsonArray = new JSONArray();
        if (!CollectionUtils.isEmpty(enquiryList)){
            enquiryList.forEach(item -> {
                JSONObject js = new JSONObject();
                js.put("id",item.getId());
                js.put("createDate",DateUtil.format(item.getCreateDate(), "yyyy-MM-dd HH:mm"));
                js.put("contacts",item.getContacts());
                js.put("storeName",item.getStoreName());
                js.put("servicePlanId",item.getServicePlanId());
                js.put("carLicense",item.getCarLicense());
                js.put("store",item.getStore());
                js.put("vin",item.getVin());
                js.put("type",item.getType());
                if (!ObjectUtils.isEmpty(item.getVehicleConfig()) && !ObjectUtils.isEmpty(item.getVehicleConfig().getCarModel())){
                    js.put("carModelName",item.getVehicleConfig().getCarModel().getName() + item.getVehicleConfig().getName());
                }
                JSONObject jsonObject = JSON.parseObject(invoke("cm.deptOfferGroupService.findByDeptId", MapUtil.mapper("deptId",item.getStore())));
                if(jsonObject.getString("body")!=null){
                    js.put("offerGroup",jsonObject.getJSONObject("body").getString("name"));
                }
                js.put("sum",item.getSum());
                List<Quote> quotes = quoteRepository.findAllByEnquiryId(item.getId());
                int finish = 0;
                int unfinish = 0;
                if (!CollectionUtils.isEmpty(quotes)){
                    finish = (int) quotes.stream().filter(f -> "finish".equals(f.getState())).count();
                    unfinish = (int) quotes.stream().filter(f -> "ing".equals(f.getState()) || "expired".equals(f.getState())).count();
                }
                int count = finish+unfinish;
                String quotation = "应报 " + count + " 已报 " + finish + " 未报 " + unfinish;
                js.put("quotationInfo",quotation);
                js.put("state",item.getState());
                jsonArray.add(js);
            });
        }
        return jsonArray;
    }

    /**
     * 封装询价查询条件
     * @param requestJO
     * @return
     */
    private JSONObject packagingData(JSONObject requestJO){
        JSONObject jo = new JSONObject();

        JSONArray jsonArray = requestJO.getJSONArray("condition");
        if (!CollectionUtils.isEmpty(jsonArray)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = (JSONObject) jsonArray.get(i);
                if (json.getString("field").equals("CREATE_DATE")){
                    if(json.getString("operator").equals("GTE")){
                        jo.put("CREATE_BIGEND_START", DateUtil.parse(json.getString("value"), DateUtil.SHOW_DATETIME_FORMAT));
                    }else {
                        jo.put("CREATE_BIGEND_END", DateUtil.parse(json.getString("value"), DateUtil.SHOW_DATETIME_FORMAT));
                    }

                }
                if (json.getString("field").equals("STORE")){
                    jo.put("STORE", json.getString("value"));
                }
                if (json.getString("field").equals("CAR_LICENSE")){
                    jo.put("CAR_LICENSE", json.getString("value"));
                }
                if (json.getString("field").equals("VIN")){
                    jo.put("VIN", json.getString("value"));
                }
                if (json.getString("field").equals("ID")){
                    jo.put("ID", json.getString("value"));
                }
                if (json.getString("field").equals("STATUS")){
                    jo.put("STATUS", json.getString("value"));
                }
                if (json.getString("field").equals("CONTACT")){
                    jo.put("CONTACT", json.getString("value"));
                }
                if (json.getString("field").equals("ENQUIRY_GROUP")){
                    jo.put("ENQUIRY_GROUP", json.getString("value"));
                }
                if (json.getString("field").equals("store")){
                    jo.put("store", json.getString("value"));
                }
                if (json.getString("field").equals("offerGroup")){
                    jo.put("offerGroup", json.getString("value"));
                }
                if (json.getString("field").equals("SOURCE")){
                    jo.put("servicePlanId", json.getString("value"));
                }
            }
        }
        return jo;
    }


    /**
     *终止报价明细
     * @param request
     * @return
     */
    public Map terminationQuoteResult(SimpleRequest request){
        JSONObject jo = request.getJO().getJSONObject("data");
        QuoteResult quoteResult = quoteResultRepository.findOne(jo.getString("id"));
        quoteResult.setState("20");
        quoteResultRepository.saveAndFlush(quoteResult);
        JSONObject data = request.getJO().getJSONObject("data");
        data.remove("id");
        data.put("id",request.getJO().getJSONObject("data").getString("enquiryId"));
        data.put("page",0);
        request.setBody(data.toString());
       return  findOneEnquiry(request);

    }

    /**
     * 根据询价ID查询明细
     * @param request
     * @return
     */
    public List<EnquiryItem> findEnquiryItemList(SimpleRequest request){
        String  id = request.getJO().getString("id");
        List<EnquiryItem> list =  enquiryItemRepository.findByEnquiryId(id);
        for (EnquiryItem enquiryItem:list) {
            //询价需求
            EnquiryRequire enquiryRequire = enquiryRequireRepository.findOne(enquiryItem.getEnquiryRequireId());
            enquiryItem.setQty(enquiryRequire.getQty());
            enquiryItem.setNote(enquiryRequire.getNote());
            if(enquiryItem.getCategoryId()==null)continue;
            enquiryItem.setCategory(categoryRepository.findOne(enquiryItem.getCategoryId()));
        }
        return  list;
    }

    /**
     * 重新推单
     * @param request
     * @return
     */
    public boolean enquiryAnewPush(SimpleRequest request){
        JSONObject jo = request.getJO().getJSONObject("data");
       JSONArray partyRoleArray =  jo.getJSONArray("suppliers");
        JSONArray enquiryItemArray = jo.getJSONArray("enquiryItems");

        JSONArray enquiryItems = enquiryItemArray.stream().filter(item -> {
            JSONObject o = (JSONObject)item;
            return o.getString("selected")!=null && o.getBoolean("selected");}).collect(Collectors.toCollection(JSONArray::new));
        if(enquiryItems.size()<=0) return false;

        String enquiryId = enquiryItems.getJSONObject(0).getString("enquiryId");
        Enquiry enquiry = enquiryRepository.findOne(enquiryId);
        BusinessParam businessParam = businessParamRepository.findOne("1");
        Date quoteExpireDate = DateUtil.add(new Date(), DAY_OF_MONTH, Integer.parseInt(businessParam.getValue()));//系统时间+7天
        enquiry.setQuoteExpireDate(quoteExpireDate);
        enquiry.setState("ing");
        enquiry.setRepeatedlyOrderDate(new Date());
        enquiryRepository.saveAndFlush(enquiry);
        for (Object  partyRoleObject:partyRoleArray) {
            JSONObject partyRole = (JSONObject) partyRoleObject;
            String supplierId = partyRole.getString("id");

            Quote quote =  quoteRepository.findOneByEnquiryAndSupplier(enquiryId, supplierId);
            if (quote == null) {
                quote = new Quote();
                quote.setEnquiryId(enquiryId);
                quote.setPartyRoleId(partyRole.getString("id"));
            }
            quote.setState("ing");
            quote =  quoteRepository.saveAndFlush(quote);

            for (Object enquiryItemObject:enquiryItems) {
                JSONObject enquiryItem = (JSONObject)enquiryItemObject;
                String enquiryRequireId = enquiryItem.getString("enquiryRequireId");
                List<QuoteItem> quoteItemHistorys = quoteItemRepository.findQuoteIdAndSupplierAndCategory(supplierId, enquiryRequireId, quote.getId());
                if (!quoteItemHistorys.isEmpty()) continue;

                QuoteItem quoteItem = new QuoteItem();
                quoteItem.setPartyRoleId(partyRole.getString("id"));
                quoteItem.setQuoteId(quote.getId());
                quoteItem.setEnquiryItemId(enquiryItem.getString("id"));
                quoteItem.setEnquiryRequireId(enquiryItem.getString("enquiryRequireId"));
                quoteItem.setRecognitionState("not");
                quoteItem.setQuoteState("not");
                quoteItemRepository.saveAndFlush(quoteItem);
            }
        }
        return true;
    }

}
